package com.tc.nio.c4;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @Auther: tianchao
 * @Date: 2022/2/8 10:30
 * @Description:
 */
public class WriteServer  {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        final Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));

        while (true){
            //阻塞 来事件了往下进行
            selector.select();
            final Iterator<SelectionKey> iterator =
                    selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                final SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if (selectionKey.isAcceptable()){
                    // selectionKey.channel() == ssc 等价于 ssc.accept();
                    ServerSocketChannel channel = (ServerSocketChannel)selectionKey.channel();
                    final SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    // 向客户端发送的大量数据
                    StringBuffer stringBuffer = new StringBuffer();
                    for (int i = 0; i < 30000000; i++) {
                        stringBuffer.append("a");
                    }
                    final ByteBuffer byteBuffer = Charset.defaultCharset().encode(stringBuffer.toString());
                    //write 方法不能保证一次就把所有内容写到客户端中****
                    //实际写的字节数 是返回值
                    while (byteBuffer.hasRemaining()){
                        // 向通道中写数据
                        int write = sc.write(byteBuffer);
                        System.out.println(write);
                    }

                }

            }
        }
    }
}
